//
//  HOPComposeViewController.swift
//  WB01
//
//  Created by HOP on 15/12/24.
//  Copyright © 2015年 HOP. All rights reserved.
//

import UIKit

import SVProgressHUD

class HOPComposeViewController: UIViewController {
    // MARK: - 点击事件
    /// toolBar底部约束
    private var toolBarBottomCon: NSLayoutConstraint?
/// 微博最大的长度
    private let maxTipLength = 25
     /// 照片选择器的view的底部约束
    private var photoSelectorViewBottomCon: NSLayoutConstraint?
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        self.addChildViewController(photoSelectorVC)
        self.addChildViewController(emoticonVC)
        setUpNav()
        setUpTextView()
        setUpPhotoBrowser()
        setUpToolBar()
        setupTipLengthLabel()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "WillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 显示剩余文字长度
        tipLengthLabel.text = String(maxTipLength)
    }
    deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 照片选择器没有出现的时候,就弹出键盘
        if photoSelectorViewBottomCon?.constant != 0 {
        // 说明照片选择器的view看不到
        // 弹出键盘
        print("textView: \(textView.inputView)")
        textView.becomeFirstResponder()
        }
        
    }
    /// 设置照片选择器
   private func setUpPhotoBrowser() {
    let photoSelectorView = photoSelectorVC.view
    // 添加子控件
    view.addSubview(photoSelectorView)
    // 约束
    photoSelectorView.translatesAutoresizingMaskIntoConstraints = false
    // 水平填充父控件
  view.addConstraints( NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[psv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["psv" : photoSelectorView]))
    // 垂直方向,高度是父控件的60%
    view.addConstraint( NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: view.frame.height * 0.6))
    // 底部和父控件底部重合，往下移动照片选择器的高度
    photoSelectorViewBottomCon = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant:view.frame.height * 0.6)
    view.addConstraint(photoSelectorViewBottomCon!)
    
    }
    /// 设置提示文字长度的label
    private func setupTipLengthLabel() {
    view.addSubview(tipLengthLabel)
    tipLengthLabel.ff_AlignVertical(type: ff_AlignType.TopRight, referView: ToolBar, size: nil, offset: CGPoint(x: -4, y: -4))
    }
    //添加ToolBar
    private func setUpToolBar() {
    //添加控件
    view.addSubview(ToolBar)
    //设置约束
   let cons = ToolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolBarBottomCon = ToolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        // 每个item对应的图片名称, 数组里面有5个字典 imageName 对应的value就是要显示的图片
        let itemSettings = [["imageName": "compose_toolbar_picture","action": "picture"],
            ["imageName": "compose_trendbutton_background","action": "trend"],
            ["imageName": "compose_mentionbutton_background","action": "mention"],
            ["imageName": "compose_emoticonbutton_background","action": "emoticon"],
            ["imageName": "compose_addbutton_background","action": "add"]]
        var items = [UIBarButtonItem]()
        // 遍历数组,获取图片的名称
        for dict in itemSettings {
        let imageName = dict["imageName"]!
        let action = dict["action"]!
        // 创建UIBarButtonItem
        let item = UIBarButtonItem(imageName: imageName)
            // 给item里面的按钮添加点击事件
            let button = item.customView as? UIButton
            // action: 如果是字符串,可以直接使用,如果是一个变量或常量,需要使用Selector
            button?.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            // 不要直接appent,因为 toolBar.items 没有值
            //            toolBar.items?.append(newElement: Element)
            items.append(item)
            // 添加弹簧
            let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(flexibleSpace)
        }
        // 移除最后一根弹簧
            items.removeLast()
            ToolBar.items = items
      }
    func picture() {
    // 让照片选择器的view回到上面来
    photoSelectorViewBottomCon?.constant = 0
        // 把键盘退下
        textView.resignFirstResponder()
        // 动画
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    func trend() {
        print("#")
        
    }
    func mention() {
        print("@")
        
    }
    /*
    textView弹出键盘之前:
    1.如果inputView == nil,会弹系统的键盘
    2.如果inputView != nil,弹对应的键盘
    */
    /// 切换键盘

    func emoticon() {
        print("textView.inputView: \(textView.inputView)")
        // 将键盘退回,如果退出键盘和弹出键盘事件相差很短,不会有退回去和弹出来的动画
        textView.resignFirstResponder()
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
        self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
        // 再次弹出键盘
        self.textView.becomeFirstResponder()
        }
    }
    func add () {
        print("加号")
        
    }
//    notice: NSConcreteNotification 0x7f9a2ab5c610 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
//    UIKeyboardAnimationCurveUserInfoKey = 7;
//    UIKeyboardAnimationDurationUserInfoKey = "0.25";
//    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
//    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
//    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
//    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
//    UIKeyboardIsLocalUserInfoKey = 1;
//    }}
    func WillChangeFrame(notice: NSNotification) {
//    print("notice: \(notice)")
    // 获取动画时间
    let duration = notice.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
    // 获取键盘的最终位置
        let frame = notice.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
    toolBarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
//    添加导航栏
    private func setUpNav() {
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        setUpTitle()
    navigationItem.rightBarButtonItem?.enabled = false
     }
    private func setUpTitle() {
    let name = HOPuserAccount.userAccount?.screen_name ?? "没有获取到用户名"
    let titleName = "转微博" + "\n" + name
    let label = UILabel()
        label.textColor = UIColor.blackColor()
        label.font = UIFont.systemFontOfSize(18)
        label.textAlignment = NSTextAlignment.Center
        label.numberOfLines = 0
    
    let title = NSMutableAttributedString(string: titleName)
    let  range = (titleName as NSString).rangeOfString(name)
        title.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
        title.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
        
        label.attributedText = title
        label.sizeToFit()
        navigationItem.titleView = label
    }
    private func setUpTextView() {
    //添加控件
    view.addSubview(textView)
    textView.delegate = self
//        设置约束
    textView.ff_Fill(view)
    }
//    取消
    func close() {
    textView.resignFirstResponder()
    dismissViewControllerAnimated(true, completion: nil)
    }
//    发送
    func sendStatus() {
    let text = textView.emoticonText()
        // 获取照片选择器的图片,获取第一张
        let image = photoSelectorVC.photos.first
        // 如果微博内容超出长度,提示用户
        if maxTipLength - text.characters.count < 0 {
        SVProgressHUD.showErrorWithStatus("微博内容超出长度")
        return
        }
    // 提示用户正在发送微博
      SVProgressHUD.showWithStatus("正在发送微博...")
        // 发送微博
        HOPNetworkTools.sharedInstance.sendStatus(text, image: image) { (result, error) -> () in
            if error != nil {
                print("error: \(error)")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            // 发送成功,关闭控制器
            SVProgressHUD.showSuccessWithStatus("发送微博成功...")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.close()
            })
        }
    }
    //懒加载
    private lazy var textView:  HOPPlaceholderTextView = {
    let textView = HOPPlaceholderTextView()
    textView.backgroundColor = UIColor.brownColor()
    textView.alwaysBounceVertical = true
    textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
    textView.font = UIFont.systemFontOfSize(18)
    textView.placeholderText = "分享新鲜事..."
    return textView
    }()
    private lazy var ToolBar: UIToolbar = {
    let ToolBar = UIToolbar()
    ToolBar.backgroundColor = UIColor.whiteColor()
    return ToolBar
    }()
    /// 剩余文字数量的label
    private lazy var tipLengthLabel: UILabel = {
    let label = UILabel()
       // 设置字体
        label.font = UIFont.systemFontOfSize(13)
         // 设置颜色
        label.textColor = UIColor.lightGrayColor()
    return label
    }()
    //懒加载图片选择器
    private lazy var photoSelectorVC: HOPPhotoSelectController = HOPPhotoSelectController()
    //懒加载表情键盘
    private lazy var emoticonVC: HOPEmoticonViewController = HOPEmoticonViewController(textView: self.textView)
}
extension HOPComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        // 设置导航栏右边按钮的可用和不可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        // 获取textView现有的文字数量
        let count = textView.emoticonText().characters.count
        // 用最大文字数量 - 现有文字数量
        let length = maxTipLength - count
        // 设置剩余文字数量
        tipLengthLabel.text = String(length)
        // 如果剩余数量小于0显示红色,否则显示灰色
        tipLengthLabel.textColor = length < 0 ? UIColor.redColor() : UIColor.lightGrayColor()

    }

}









